<template>
  <div class="projectDetail">
    <div class="breadcrumbNav">
      <vBreadcrumb :breadcrumb="breadcrumb"></vBreadcrumb>
    </div>
    <div class="projectTable">
      <div class="stepsDiv">
        <p class="title"><span><i>【{{progressData.status}}】</i>{{progressData.projectName}}（{{progressData.contractNo}}）</span></p>
        <el-steps :space="100" :active="progressData.step" finish-status="success">
          <el-step v-for="(item, index) in progressData.steps" :title="item" :key="index"></el-step>
        </el-steps>
      </div>
      <div class="operation">
        <button @click="editToggle" :disabled="!canEdit"><span v-show="!isEdit">编辑</span><span v-show="isEdit">完成</span></button>
      </div>
      <div class="table">
        <el-table :data="tableData" border>
          <el-table-column v-for="(item,index) in table" :label="item.label" :key="index"
                           :sortable="item.sortable ? true : false" :prop="item.name">
            <template scope="scope">
              <span v-if="item.name === 'process'">
                <span :title="scope.row[item.name]">{{ scope.row[item.name] }}</span>
              </span>
              <p v-else v-for="(item2, index2) in scope.row['children']" :title="scope.row['children'][index2][item.name]">
                <span v-if="scope.row['children'][index2]['taskName'] !== '' && scope.row['children'][index2][item.name] === 'operation'">
                  <a href="#" v-show="!isEdit" class="detailLink detail"
                     @click="toDetail(scope.row, scope.row['children'][index2])">详情</a>
                  <a href="#" v-show="isEdit" class="detailLink update"
                     @click="toEdit(scope.row['children'], scope.row['children'][index2])">编辑</a>
                  <a href="#" v-show="isEdit"
                     @click="confirmPop(scope.row['children'], index2, scope.row['children'][index2])">
                    <span class="deleteLink"></span>
                  </a>
                </span>
                <span v-else-if="scope.row['children'][index2]['taskName'] === ''"></span>
                <span v-else>
                  {{ scope.row['children'][index2][item.name] }}
                </span>
              </p>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!--详情弹窗-->
      <el-dialog v-model="dialogFormShow" title="详情" @close="dialogFormClose" top="70px">
        <div class="item-dialog">
          <el-form :model="detailForm" :rules="rules" ref="detailForm" label-width="94px" label-position="right">
            <el-row>
              <el-col :span="12">
                <el-form-item  label="是否已完成" prop="status">
                  <el-radio-group v-model="detailForm.status" @change="detailForm.status = parseInt(detailForm.status)" :disabled="!isEdit" >
                    <el-radio :label="1">是</el-radio>
                    <el-radio :label="0">否</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="完成时间">
                  <el-date-picker  v-model="detailForm.completeTime"  type="date"  placeholder="选择日期"  @input="dateChange" :disabled="!isEdit"></el-date-picker>
                </el-form-item>
                <el-form-item label="负责人">
                  <el-input v-model="detailForm.dutyPerson" placeholder="请填写负责人姓名" :disabled="!isEdit"></el-input>
                </el-form-item>
                <el-form-item label="遇到的问题">
                  <el-input type="textarea" v-model="detailForm.problem" placeholder="请填写问题" :disabled="!isEdit"></el-input>
                </el-form-item>
                <el-form-item label="交接人" prop="handoverPerson">
                  <el-input v-model="detailForm.handoverPerson" placeholder="请填写交接人姓名" :disabled="!isEdit"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item v-for="(item, index) in detailForm.extInfo" :label="item.fieldName" :key="index">
                  <el-date-picker v-show="item.fieldType === '日期'"  v-model="item.content"  type="date"  placeholder="选择日期" @input="dateScopeChange(index, item.content)" :disabled="!isEdit"></el-date-picker>
                  <el-input v-show="item.fieldType === '文本'" v-model="item.content" :disabled="!isEdit"></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button icon="plus" class="addFieldBtn" @click="addData=true" :disabled="!isEdit">新增字段</el-button>
                  <div class="new-add-edit" v-show="addData">
                    <el-form :model="addItem" ref="addItem" :rules="addRules">
                      <el-form-item prop="fieldName">
                        <el-input v-model="addItem.fieldName" placeholder="请填写字段名称"></el-input>
                      </el-form-item>
                      <el-form-item prop="fieldType">
                        <el-select v-model="addItem.fieldType"  placeholder="请选择字段类型">
                          <el-option v-for="(item, index2) in feildTypeOptions" :label="item.label" :value="item.value" :key="index2"></el-option>
                        </el-select>
                      </el-form-item>
                      <el-form-item>
                        <el-button class="new-btn-no buleSpaceBtn" @click="addData=false">取消</el-button>
                        <el-button class="new-btn-ok buleBtn" @click="addDataHandler('addItem')">完成</el-button>
                      </el-form-item>
                    </el-form>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row v-show="isEdit">
              <el-col :span="24">
                <div class="dialog-submit">
                  <el-button class="submitBtn" @click="submitForm('detailForm')">完成</el-button>
                </div>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
  import ajax from '../../../utils/ajax/index'
  import copyObject from '../../../utils/copyObject/copyObject'
  import setDate from '../../../utils/date/setDate'
  import vBreadcrumb from '../../common/breadcrumb.vue'
  export default {
    components: { vBreadcrumb },
    data () {
      return {
        breadcrumb: [
          {
            name: '项目总览',
            path: 'cityList'
          },
          {
            name: '项目列表',
            path: 'projectList'
          },
          {
            name: '总览详情',
            path: 'projectDetail'
          }
        ],
        dialogFormShow: false,
        obj: {},
        detailForm: {
          status: 0,
          completeTime: '',
          dutyPerson: '',
          problem: '',
          handoverPerson: '',
          extInfo: []
        },
        progressData: {
          status: '',
          projectName: '',
          contractNo: '',
          step: '',
          steps: []
        },
        table: [
          {label: '项目流程', name: 'process'},
          {label: '流程详情', name: 'taskName'},
          {label: '完成时间', name: 'completeTime'},
          {label: '负责人', name: 'dutyPerson'},
          {label: '遇到的问题', name: 'problem'},
          {label: '交接人', name: 'handoverPerson'},
          {label: '操作', name: 'operation'}
        ],
        tableData: [],
        isEdit: false,  // 是否可编辑表单
        editIndex: null, // 编辑的第几个任务
        eidtRows: null,  // 保存编辑的那个流程的任务,
        cityId: '',
        addData: false,
        addItem: {
          fieldName: '',
          fieldType: '',
          content: '',
          key: Date.now()
        },
        feildTypeOptions: [{
          value: '日期',
          label: '日期'
        }, {
          value: '文本',
          label: '文本'
        }],
        rules: {
          status: [
            { required: true, type: 'integer', message: '请选择任务状态', toggle: 'blur' }
          ],
          handoverPerson: [
            { required: true, message: '请选择交接人', toggle: 'blur' }
          ]
        },
        addRules: {
          projectCode: [
            { required: true, message: '请填写字段名称', toggle: 'blur' }
          ],
          processName: [
            { required: true, message: '请选择字段类型', toggle: 'blur' }
          ]
        },
        canEdit: true
      }
    },
    mounted () {
      this.initSteps()
      this.result()
    },
    methods: {
      result () {
        let that = this
        let projectCode = that.$route.query.projectCode // 获取url后面的参数项目编号
        that.progressData.status = that.$route.query.projectStatus // 获取url后面的参数项目状态
        that.canEdit = that.progressData.status === '进行中'
        that.cityId = that.$route.query.cityId
        that.breadcrumb[1].path += '?id=' + that.cityId
        let url = that.api.projectDetail.result
        let store = that.$store
        ajax.get(url, {projectCode: projectCode}, store, true).then((res) => {
          let tableData = res.data
          for (let i = 0; i < tableData.length; i++) {
            let step = tableData[i].process.split('-')[1]
            that.progressData.steps.push(step)
          }
          let processName = that.$route.query.processName // 获取url后面的参数当前流程名
          that.progressData.step = that.progressData.status === '进行中' ? that.progressData.steps.indexOf(processName) : that.progressData.steps.length
          that.tableData = tableData
        })
      },
      initSteps () {
        let projectName = this.$route.query.projectName // 获取url后面的参数项目名称
        let contractNo = this.$route.query.contractNo // 获取url后面的参数项目名称
        this.progressData.projectName = projectName
        this.progressData.contractNo = contractNo
      },
      editToggle (that) {
        this.isEdit = !this.isEdit
      },
      toDetail (row, subProgressData) { // 详情
        this.dialogFormShow = true
        this.detailForm = copyObject(subProgressData)
      },
      toEdit (rows, subProgressData) { // 编辑
        this.dialogFormShow = true
        this.detailForm = copyObject(subProgressData)
        this.eidtRows = rows
        this.editIndex = rows.indexOf(subProgressData)
      },
      submitForm (formName) { // 提交编辑
        let that = this
        let confirm = that.$confirm
        let msg = that.$message
        let url = that.api.projectDetail.saveOrUpdate
        let object = copyObject(that.detailForm)
        object.extInfo = JSON.stringify(object.extInfo)
        that.$refs[formName].validate((valid) => {
          if (valid) { // 通过验证
            confirm('是否继续?', '提示', {confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'})
              .then(() => {
                ajax.post(url, object, false).then((res) => {
                  if (res.msg.code === '20000') {
                    that.eidtRows.splice(that.editIndex, 1, object)
                    msg({type: 'success', message: '任务修改成功！'})
                    that.dialogFormClose()
                  } else {
                    msg({type: 'error', message: res.msg.message})
                  }
                })
              }).catch(() => {})
          } else {
            // 未通过验证
            msg({type: 'error', message: '必填项填写有误！'})
          }
        })
      },
      dialogFormClose () { // 关闭新增弹窗
        this.$refs.detailForm.resetFields()
        this.$refs.detailForm.extInfo = []
        this.dialogFormShow = false
        this.isEdit = false
      },
      dateChange (val) {
        this.detailForm.completeTime = setDate(val)
      },
      dateScopeChange (index, val) {
        this.detailForm.extInfo[index].content = setDate(val)
      },
      confirmPop (row, index, subRow) { // 删除
        let that = this
        let store = that.$store
        let url = that.api.projectDetail.delete
        this.$confirm('您确认删除该条信息?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          ajax.post(url, {id: subRow.id}, store).then((res) => {
            if (res.msg.code === '20000') {
              that.$message({type: 'success', message: '删除成功'})
              row.splice(index, 1)
            } else {
              that.$message({type: 'error', message: res.msg.message})
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      addDataHandler (formName) {
        if (this.addItem.fieldName === '' || this.addItem.fieldType === '') {
          this.$message({
            type: 'warning',
            message: '字段名称或字段类型未填！'
          })
        } else {
          // 通过验证
          this.detailForm.extInfo.push(this.addItem)
          this.addData = false
        }
      }
    }
  }
</script>
